<!--
 * 兑现商品详情
-->
<template>
  <div class="adminSet">
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="200px"
      class="demo-ruleForm"
    >
      <el-tabs v-model="attrType" type="card" @tab-click="tabChange">
        <el-row>
          <el-col :span="24" style="text-align: center; margin-top: 0px">
            <el-button
              class="float-button"
              type="primary"
              size="mini"
              round
              @click="resetForm()"
              >返回
            </el-button>
          </el-col>
        </el-row>
        <el-tab-pane label="基本信息" name="first">
          <el-form-item label="商品名称" prop="goodsName">
            <el-input
              v-model="ruleForm.goodsName"
              class="input_edit"
              placeholder="请选择"
              disabled
            />
          </el-form-item>

          <el-form-item label="国际条码" prop="barCode">
            <el-input
              v-model="ruleForm.barCode"
              class="input_edit"
              :maxlength="30"
              disabled
            >
            </el-input>
          </el-form-item>

          <el-form-item label="会员价" prop="memberPrice">
            <el-input
              v-model="ruleForm.memberPrice"
              :maxlength="10"
              class="input_edit"
              style="text-align-last: right"
              placeholder="会员价"
              disabled
            >
              <template slot="append">元</template>
            </el-input>
          </el-form-item>

          <el-form-item label="库存数量" prop="repertory">
            <el-input v-model="ruleForm.repertory" disabled class="input_edit" />
            <p class="tips">
              （-1代表不限制库存）
            </p>
          </el-form-item>

          <el-form-item label="商品单位" prop="unit">
            <el-select v-model="ruleForm.unit" disabled class="input_edit">
              <el-option
                v-for="(send, i) in unitData"
                :key="i"
                :value="send.uuid"
                :label="send.unitName"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="展示顺序" prop="sortNo">
            <el-input
              v-model="ruleForm.sortNo"
              :maxlength="4"
              class="input_edit"
              style="text-align-last: right"
              :min="1"
              disabled
            ></el-input>
          </el-form-item>

          <el-form-item
            v-if="ruleForm.types == 1"
            label="云币兑换比例"
            prop="scale"
          >
            <el-input-number
              v-model="ruleForm.scale"
              class="input_edit"
              :min="0"
              :max="100"
              disabled
            />%
          </el-form-item>

          <!-- <el-form-item label="是否最小单位" prop="isMinUnit">
            <el-radio v-model="ruleForm.isMinUnit" disabled label="1">是</el-radio>
            <el-radio v-model="ruleForm.isMinUnit" disabled label="0">否</el-radio>
          </el-form-item> -->

          <el-form-item label="限购数量" prop="purchaseLimitation">
            <el-input
              v-model="ruleForm.purchaseLimitation"
              class="input_edit"
              disabled
            />
            <p class="tips">
              （-1代表不限购）
            </p>
          </el-form-item>

          <el-form-item
            v-if="ruleForm.types == 0"
            label="酒币兑换比例"
            prop="scale"
          >
            <el-input-number
              v-model="ruleForm.scale"
              class="input_edit"
              :min="0"
              :max="100"
              disabled
            />%
          </el-form-item>

          <el-form-item label="商品分类" prop="goodsTypeId">
            <el-select v-model="ruleForm.goodsTypeId" class="input_edit" disabled>
              <el-option v-for="(send, i) in exchangeTypeList" :key="i" :value="send.goodsTypeId" :label="send.goodsTypeName">
              </el-option>
            </el-select>
          </el-form-item>
        </el-tab-pane>

        <el-tab-pane label="详细信息" name="second">
          <el-form-item>
            <span
              style="
                margin-left: 0%;
                margin-top: 22%;
                margin-bottom: 20px;
                font-size: 20px;
                color: #000000;"
            ></span>
          </el-form-item>

          <el-form-item label="商品主图" prop required>
            <el-row>
              <el-col style="margin: 10px; 0px; 10px; 0">
                <el-upload
                  style="margin: 10px"
                  :action="action"
                  :limit="1"
                  list-type="picture-card"
                  :on-preview="handlePreview"
                  :file-list="fileList6"
                  disabled
                >
                  <i class="el-icon-plus"></i>
                </el-upload>
                <p class="tips">
                  注：上传图片(限30M) 图片将用于消费者端商品列标图
                </p>
              </el-col>
            </el-row>
          </el-form-item>

          <el-form-item label="详情图片" prop required>
            <el-row>
              <el-col style="margin: 10px; 0px; 10px; 0">
                <el-upload
                  style="margin: 10px"
                  :action="action"
                  :limit="1"
                  list-type="picture-card"
                  :on-preview="handlePreview"
                  :file-list="fileList3"
                  disabled
                >
                  <i class="el-icon-plus"></i>
                </el-upload>
                <p class="tips">
                  注：上传图片(限30M) 图片将用于消费者端产品详情图页
                </p>
              </el-col>
            </el-row>
          </el-form-item>

          <el-form-item label="商品展示图" prop required>
            <el-row>
              <el-col style="margin: 10px; 0px; 10px; 0">
                <draggable
                  class="list-group"
                  tag="ul"
                  v-model="fileList2"
                  v-bind="dragOptions"
                  @start="drag = true"
                  @end="drag = false"
                >
                  <div
                    class="img-wrapper divBox"
                    v-for="(item, index) in fileList2"
                  >
                    <img
                      :src="item.url"
                      v-if="item.url"
                      width="148"
                      height="148"
                      class="imgSty"
                      @click="handlePreview(item)"
                    />
                  </div>
                </draggable>
              </el-col>
            </el-row>
          </el-form-item>
        </el-tab-pane>

        <el-tab-pane label="扩展信息" name="third">
          <vue-ueditor-wrap
            v-model="ruleForm.goodsDescribe"
            :config="myConfig"
            @ready="ready"
            :destroy="true"
          >
          </vue-ueditor-wrap>
        </el-tab-pane>

        <el-row>
          <el-col :span="24" style="text-align: center; margin-top: 30px">
            <el-button @click="resetForm()" size="mini">取消</el-button>
          </el-col>
        </el-row>
      </el-tabs>
    </el-form>

    <el-dialog :visible.sync="dialogVisibleImg" size="tiny">
      <img width="100%" :src="dialogImageUrl" alt />
    </el-dialog>
  </div>
</template>

<script>
import draggable from 'vuedraggable';
import VueUeditorWrap from 'vue-ueditor-wrap';
import { getProductUnitList } from '@/api/compositegoods';
import { updateExchange, getExchangeDetail, queryGoodsExchangeTypeList } from '@/api/goodsExchange';

const isMoney = function(rule, value, callback) {
  const reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
  if (!value) {
    return callback(new Error('金额不能为空'));
  } else if (!reg.test(value)) {
    return callback(new Error('金额格式错误'));
  } else {
    callback();
  }
};
export default {
  components: {
    VueUeditorWrap,
    draggable,
  },
  data() {
    return {
      action: `${process.env.VUE_APP_BASE_API}/api/file-service/v1/file/uploadFile`,
      active: 1,
      headers: {
        token: localStorage.getItem('token'), //从cookie里获取token，并赋值  Authorization ，而不是token
      },
      unitData: [],
      exchangeTypeList: [],
      ruleForm: {
        types: 0,
        goodsName: '',
        barCode: '',
        memberPrice: '',
        repertory: '',
        unit: '',
        sortNo: '',
        scale: '',
        isMinUnit: '1',
        purchaseLimitation: '',
        goodsDescribe: '',
        goodsTypeId: '',
      },
      attrType: 'first',
      // 是否可以编辑
      editflag: true,

      // 上传相关
      fileList6: [], // 商品主图
      fileList2: [], // 商品展示图
      fileList3: [], // 商品详情图
      dialogVisibleImg: false, // 图片预览弹框
      dialogImageUrl: '', // 图片预览地址

      myConfig: {
        // 编辑器不自动被内容撑高
        autoHeightEnabled: false,
        // 初始容器高度
        initialFrameHeight: 240,
        // 初始容器宽度
        initialFrameWidth: '100%',
        // 上传文件接口（这个地址是我为了方便各位体验文件上传功能搭建的临时接口，请勿在生产环境使用！！！）
        //   serverUrl: 'http://35.201.165.105:8000/controller.php',
        serverUrl: `${process.env.VUE_APP_BASE_API}/api/file-service/v1/file/uploadFile`,
        // UEditor 资源文件的存放路径，如果你使用的是 vue-cli 生成的项目，通常不需要设置该选项，vue-ueditor-wrap 会自动处理常见的情况，如果需要特殊配置，参考下方的常见问题2
        UEDITOR_HOME_URL:
          process.env.NODE_ENV == 'production'
            ? '../../ui/static/UEditor/'
            : '../../static/UEditor/',
        // UEDITOR_HOME_URL: "../../static/UEditor/"
      },
    };
  },
  computed: {
    dragOptions() {
      return {
        animation: 200,
        group: 'description',
        disabled: false,
        ghostClass: 'ghost',
      };
    },
    rules() {
      const scaleMesaage =
        this.ruleForm.types == 1 ? '请输入云币兑换比例' : '请输入酒币兑换比例';
      return {
        goodsName: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
        ],
        memberPrice: [
          { required: true, message: '请输入会员价', trigger: 'blur' },
          { validator: isMoney, trigger: 'blur' },
        ],
        repertory: [
          { required: true, message: '请输入库存数量', trigger: 'blur' },
        ],
        unit: [
          { required: true, message: '请选择商品单位', trigger: 'change' },
        ],
        goodsTypeId: [
          { required: true, message: '请选择商品分类', trigger: 'change' },
        ],
        scale: [
          {
            type: 'number',
            required: true,
            message: scaleMesaage,
            trigger: 'blur',
          },
        ],
        isMinUnit: [
          { required: true, message: '请选择是否最小单位', trigger: 'change' },
        ],
        purchaseLimitation: [
          {
            type: 'number',
            required: true,
            message: '请输入限购数量',
            trigger: 'blur',
          },
        ],
      };
    },
  },
  created() {
    this.getProductUnit();
    if (this.$route.params.types) {
      this.ruleForm.types = this.$route.params.types;
      this.rules.scale[0].message =
        this.ruleForm.types == 1 ? '请输入云币兑换比例' : '请输入酒币兑换比例';
    }
    if (this.$route.params.uuid) {
      this.getDetail(this.$route.params.uuid);
    }

    this.getExchangeTypeList();
  },
  methods: {
    getDetail(id) {
      getExchangeDetail({
        id,
      }).then((res) => {
        this.ruleForm.goodsName = res.result.goodsName;
        this.ruleForm.barCode = res.result.barCode;
        this.ruleForm.memberPrice = res.result.memberPrice;
        this.ruleForm.repertory = res.result.repertory;
        this.ruleForm.unit = res.result.unit;
        this.ruleForm.sortNo = res.result.sortNo;
        this.ruleForm.scale = res.result.scale;
        this.ruleForm.isMinUnit = res.result.isMinUnit;
        this.ruleForm.purchaseLimitation = res.result.purchaseLimitation;
        this.ruleForm.goodsDescribe = res.result.goodsDescribe;
        this.ruleForm.goodsTypeId = res.result.goodsTypeId;

        let picture = res.result.picture;
        if (picture !== undefined && picture !== null) {
          var picUrl = picture.picUrl;
          var index = picUrl.lastIndexOf('.');
          var aa = picUrl.substring(index - 5, picUrl.length);
          let data = {
            name: aa,
            picId: picture.picId,
            goodsId: picture.goodsId,
            url: picture.picUrl,
          };
          this.fileList6.push(data);
        }
        let img = res.result.img;
        if (img !== undefined && img != null) {
          var picUrl = img.picUrl;
          var index = picUrl.lastIndexOf('.');
          var aa = picUrl.substring(index - 5, picUrl.length);
          let data = {
            name: aa,
            picId: img.picId,
            goodsId: img.goodsId,
            url: img.picUrl,
          };
          this.fileList3.push(data);
        }

        let pictures = res.result.pictures; //v.pictures;
        if (pictures !== undefined && pictures != null && pictures.length > 0) {
          pictures.forEach((item, i) => {
            if (item != null) {
              var picUrl = item.picUrl;
              var index = picUrl.lastIndexOf('.');
              var aa = picUrl.substring(index - 5, picUrl.length);
              var picId = item.picId;
              let data = {
                name: aa,
                url: picUrl,
                picId: picId,
                picType: 2,
              };
              this.fileList2.push(data);
            }
          });
        }
      });
    },

    //查询商品单位
    getProductUnit(v) {
      let data = {
        size: 100,
        current: 1,
        condition: {},
        ascs: [],
        descs: [],
      };
      getProductUnitList(data).then((res) => {
        this.unitData = res.records;
      });
    },

    // 商品兑换分类列表
    getExchangeTypeList() {
      const data = {
        size: 999999,
        current: 1,
        condition: {
          isDisplay: 1,
          exchangeType: this.ruleForm.types,
        },
        ascs: [],
        descs: [],
      };
      queryGoodsExchangeTypeList(data).then((res) => {
        this.exchangeTypeList = res.records;
      });
    },
    tabChange(val) {
      var name = val.name;
      if (name == 'first') {
        this.active = 1;
      } else if (name == 'second') {
        this.active = 2;
      } else if (name == 'third') {
        this.active = 3;
      } else if (name == 'fourth') {
        this.active = 4;
      }
    },

    positionTab() {
      if (this.active == 1) {
        this.attrType = 'first';
      } else if (this.active == 2) {
        this.attrType = 'second';
      } else if (this.active == 3) {
        this.attrType = 'third';
      } else if (this.active == 4) {
        this.attrType = 'fourth';
      }
    },

    prev() {
      this.active--;
      this.positionTab();
    },

    next() {
      if (this.active == 1) {
        const result = this.checkvalid();
        if (result) return;
      }
      this.active++;
      this.positionTab();
    },

    handlePreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisibleImg = true;
    },

    ready(editorInstance) {
      console.log(`编辑器实例${editorInstance.key}: `, editorInstance);
    },

    upLoadPic(file, fileList) {
      var picUrl = file.result;
      var name = fileList.name;
      let data = {
        name: name,
        url: picUrl,
        picType: 1,
      };
      this.fileList2.push(data);
    },
    upLoadPic3(file, fileList3) {
      var picUrl = file.result;
      var name = fileList3.name;
      let data = {
        name: name,
        url: picUrl,
        picType: 3,
      };
      this.fileList3.push(data);
    },
    upLoadPic6(file, fileList6) {
      var picUrl = file.result;
      var name = fileList6.name;
      let data = {
        name: name,
        url: picUrl,
        picType: 2,
      };
      this.fileList6.push(data);
    },
    //删除图片
    handleRemove(file, fileList) {
      let newfileList = [];
      fileList.forEach((item, i) => {
        let data = {
          name: item.name,
          url: item.url,
          picId: item.picId,
        };
        newfileList.push(data);
      });
      this.fileList2 = newfileList;
    },
    //删除图片
    handleRemove3(file, fileList3) {
      let newfileList = [];
      fileList3.forEach((item, i) => {
        let data = {
          name: item.name,
          url: item.url,
          picId: item.picId,
        };
        newfileList.push(data);
      });
      this.fileList3 = newfileList;
    },
    handleRemove6(file, fileList6) {
      let newfileList = [];
      fileList6.forEach((item, i) => {
        let data = {
          name: item.name,
          url: item.url,
          picId: item.picId,
        };
        newfileList.push(data);
      });
      this.fileList6 = newfileList;
    },
    handleExceed() {
      this.$message.error(`图片最多上传1张`);
    },

    // 验证
    checkvalid() {
      if (this.ruleForm.goodsName == '' || this.ruleForm.goodsName == null) {
        this.$message.error('请输入商品名称');
        return true;
      }
      if (
        this.ruleForm.memberPrice == '' ||
        this.ruleForm.memberPrice == null
      ) {
        this.$message.error('请输入会员价');
        return true;
      }
      if (this.ruleForm.repertory == '' || this.ruleForm.repertory == null) {
        this.$message.error('请输入库存数量');
        return true;
      }
      if (this.ruleForm.unit == '' || this.ruleForm.unit == null) {
        this.$message.error('请选择商品单位');
        return true;
      }
      if (this.ruleForm.scale == '' || this.ruleForm.scale == null) {
        this.$message.error(
          this.ruleForm.types == 1 ? '请输入云币兑换比例' : '请输入酒币兑换比例'
        );
        return true;
      }
      if (this.ruleForm.isMinUnit == '' || this.ruleForm.isMinUnit == null) {
        this.$message.error('请选择是否最小单位');
        return true;
      }
      if (
        this.ruleForm.purchaseLimitation == '' ||
        this.ruleForm.purchaseLimitation == null
      ) {
        this.$message.error('请输入限购数量');
        return true;
      }
    },

    // 提交
    submitForm() {
      this.checkvalid();
      if (this.fileList6 == undefined || this.fileList6.length <= 0) {
        this.$message.error('请上传商品主图');
        return;
      }
      if (this.fileList2 == undefined || this.fileList2.length <= 0) {
        this.$message.error('请上传展示图片');
        return;
      }
      if (this.fileList3 == undefined || this.fileList3.length <= 0) {
        this.$message.error('请上传商品详情');
        return;
      }

      // 图片赋值
      let pictures = [];
      this.fileList2.forEach((item, i) => {
        if (item != null) {
          let data = {
            picUrl: item.url,
            picId: item.picId,
            picType: 2,
          };
          pictures.push(data);
        }
      });
      let picture = '';
      this.fileList6.forEach((item, i) => {
        if (item != null) {
          picture = {
            picUrl: item.url,
            picId: item.picId,
            picType: 1,
          };
        }
      });

      let img = '';
      this.fileList3.forEach((item, i) => {
        img = {
          picUrl: item.url,
          picId: item.picId,
          picType: 3,
        };
      });

      let data = {
        ...this.ruleForm,
        pictures: pictures,
        picture: picture,
        img: img,
      };

      updateExchange(data).then((res) => {
        this.$message({
          showClose: true,
          message: res.message,
          type: 'success',
        });
        this.resetForm();
      });
    },

    // 取消返回
    resetForm() {
      this.$router.go(-1);
    },
  },
};
</script>

<style lang="less" scoped>
.input_edit {
  // position: relative;
  font-size: 14px;
  //display: inline-block;
  width: 300px;
}

.label_edit {
  margin-left: 50px;
}

.title {
  display: block;
  margin-left: 2%;
  margin-bottom: 2%;
  font-size: 17px;
  color: #666 !important;
}

.adminSet {
  border: 1px solid #ebeef5;
  margin-left: 5px;
  padding: 31px 0px 20px 16px;
  width: 85%;
}

.el-item:hover .el-icon-error {
  visibility: inherit;
}

.el-items .el-icon-error {
  font-size: 22px;
  padding: 10px;
  color: red;
  cursor: pointer;
  visibility: hidden;
}

.float-button {
  position: absolute; //fixed; //关键
  height: 30px;
  width: 65px;
  top: 0px;
  // bottom: 90px;
  right: 15%;
  // background: #b4d145;
  z-index: 1;
}

.tips {
  margin-left: 10px;
  color: red;
  font-size: 12px;
}

.divBox {
  /*flex-direction: row;*/
  float: left;
  position: relative;
}

.imgSty {
  margin: 10px;
}

.delIcon {
  position: absolute;
  top: 10px;
  right: 10px;
  font-size: 20px;
  color: red;
}

.form-item-inline {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  align-items: center;
}
</style>

<style>
.item .el-form-item__label {
  color: red;
}
</style>
